import cv2
import numpy as np
import json
import base64
import socket
import threading
from datetime import datetime

def save_image_from_base64(base64_str, filename):
    # 将base64字符串解码为图片
    img_data = base64.b64decode(base64_str)
    nparr = np.frombuffer(img_data, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    cv2.imwrite(filename, img)
    return img

def extract_center_20x20(img, filename):
    # 获取图片中心20x20像素区域
    height, width = img.shape[:2]
    center_x, center_y = width // 2, height // 2
    center_region = img[center_y-10:center_y+10, center_x-10:center_x+10]
    cv2.imwrite(filename, center_region)
    return center_region

def is_red_or_black(region):
    # 计算20x20区域的平均颜色
    avg_color = np.mean(region, axis=(0, 1))
    print(avg_color)
    
    # BGR颜色空间中的红色和黑色
    red_bgr = np.array([0, 0, 255])
    black_bgr = np.array([0, 0, 0])
    
    # 计算与红色和黑色的距离
    dist_red = np.linalg.norm(avg_color - red_bgr)
    dist_black = np.linalg.norm(avg_color - black_bgr)
    
    # 判断更接近哪种颜色
    return 1 if dist_red < dist_black else 0

def handle_client(conn, addr):
    try:

        
        print(f"Connection from {addr}")
        
        buffer = b''
        delimiter = b'\n'  # 或自定义分隔符
        
        while True:
            chunk = conn.recv(1024*1024*3)
            if not chunk:
                break
            buffer += chunk
            if delimiter in buffer:
                data, _, buffer = buffer.partition(delimiter)
            

                base64_str = data.decode('utf-8')
                base64_str += "=" * ((4 - len(base64_str) % 4) % 4)
                # base64_str = json_data.get('content')
                print("base64_str",base64_str)
                if base64_str.startswith("data:image/"):
                    # 提取真正的 Base64 部分（去掉 "data:image/xxx;base64,"）
                    base64_str = base64_str.split(",", 1)[1]            

            
                # 生成时间戳
                timestamp = datetime.now().strftime("%Y-%m-%d%H%M%S.%f")[:-3]
                
                # 保存原始图片
                try:
                    original_filename = f"opencvlog/{timestamp}.png"
                    img = save_image_from_base64(base64_str, original_filename)
                    print(f"Saved original image: {original_filename}")
                except Exception as e:
                    print(f"Image save error: {e}")
                    conn.send(json.dumps({"error": "Invalid image data"}).encode('utf-8'))
                    return
                    
                # 提取中心区域并保存
                try:
                    center_filename = f"opencvlog/{timestamp}+X.png"
                    center_region = extract_center_20x20(img, center_filename)
                    print(f"Saved center region: {center_filename}")
                except Exception as e:
                    print(f"Center region extract error: {e}")
                    conn.send(json.dumps({"error": "Image too small for center extraction"}).encode('utf-8'))
                    return
                    
                # 判断颜色
                result = np.mean(center_region, axis=(0, 1))
                
                # 发送结果
                response = {"result": result.tolist()}
                print(result.tolist())
                conn.send((json.dumps(response)+'\n').encode('utf-8'))
        
    except Exception as e:
        print(f"Error handling client: {e}")
    finally:
        conn.close()

def start_server():
    host = '0.0.0.0'
    port = 1885
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen()
        print(f"Server started on port {port}")
        
        while True:
            conn, addr = s.accept()
            client_thread = threading.Thread(target=handle_client, args=(conn, addr))
            client_thread.start()

if __name__ == "__main__":
    start_server()